package com.example.administrator.hqq.activity.complain;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.MyGridView;

import com.example.administrator.hqq.adapter.discover.ReleasePostAdapter;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.base.MyApplication;
import com.example.administrator.hqq.bean.Complain;
import com.example.administrator.hqq.bean.ForumComment;
import com.example.administrator.hqq.bean.QNTokenBean;
import com.example.administrator.hqq.config.LoongsConfig;

import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.example.administrator.hqq.utils.TestDataModel;
import com.example.administrator.hqq.utils.UploadManagerUtils;
import com.google.gson.Gson;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.push.RongPushClient;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import okhttp3.Call;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class ChatComplainActivity extends MyActivity {
    @BindView(R.id.return_auto)
    AutoRelativeLayout returnAuto;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.post_image)
    MyGridView postImage;
    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.chat_number)
    TextView chatNumber;
    @BindView(R.id.chat_evidence)
    AutoLinearLayout chatEvidence;
    @BindView(R.id.pic_number)
    TextView picNumber;
    @BindView(R.id.reason)
    EditText reason;
    @BindView(R.id.submit)
    Button submit;
    private List<String> url;
    private ReleasePostAdapter releasePostAdapter;
    private List<Message> messages;
    private String TAG=this.getClass().getSimpleName();
    private List<String> pic;
    private int index=0;
    private List<String> picPath;
    private String ComplaintID;

    /**
     * 跳转举报页面
     * @param activity
     * @param conversationType 聊天类型
     * @param id  聊天室targetId
     * @param objectId  举报对象的id
     * @param complainType 投诉类型
     */
    public static void start(Context activity, String conversationType, String id, String objectId, String complainType){
        Intent intent = new Intent(activity, ChatComplainActivity.class);
        intent.putExtra(LoongsConfig.ConversationType, conversationType);
        intent.putExtra(LoongsConfig.id, id);
        intent.putExtra(LoongsConfig.objectId,objectId);
        intent.putExtra(LoongsConfig.ChatComplainType, complainType);
        activity.startActivity(intent);
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_complain);
        ButterKnife.bind(this);
        //最好放到 Application oncreate执行
        initview();
        getComplaintID();
        EventBus.getDefault().register(this);
    }

    public void getComplaintID() {
        OkHttpUtils.get().url(UrlFactory.getComplaintID())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "获取投诉IDonError: "+e);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "获取投诉IDonResponse: "+response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt(LoongsConfig.code);
                    if(code==200){
                        ComplaintID=jsonObject.getString(LoongsConfig.id);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initview() {
        url = new ArrayList<>();
        messages=new ArrayList<>();
        pic=new ArrayList<>();
        releasePostAdapter = new ReleasePostAdapter(this, url);
        releasePostAdapter.setNum(9);
        postImage.setAdapter(releasePostAdapter);
        postImage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (url.size() < 9 && url.size() == i) {
                    ChatComplainActivityPermissionsDispatcher.startLocationWithCheck(ChatComplainActivity.this);
                }
            }
        });
        reason.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                int length = reason.getText().toString().length();
                if (length<200)
                {
                    number.setText(length+"/200");
                }
                else{
                    number.setText("200/200");
                }
            }
        });
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == RESULT_OK) {
                // 获取返回的图片列表
                picPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if (picPath !=null&& picPath.size()>0)
                {
                    index=0;
                    for (int i = 0; i < picPath.size(); i++) {
                        Log.e(TAG, "path: "+picPath.get(i));
                        File picFile = new File(picPath.get(i));
                        if (picFile.exists()) {

                            if (!TextUtils.isEmpty(ComplaintID))
                            {
                                showLoadingDialog();
                                getQNToken(picPath.get(i),i);
                            }
                            else{
                                getComplaintID();
                            }
                        }
                    }
                }
            }
        }
    }
    public void getQNToken(final String path, final int i) {
        showLoadingDialog();
        OkHttpUtils.get().url(UrlFactory.getQNToken())
                .addParams(LoongsConfig.type, LoongsConfig.COMPLAINT)
                .addParams(LoongsConfig.id, ComplaintID)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());
                index++;
                if (index==picPath.size())
                {
                    dismissLoadingDialog();
                    releasePostAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onResponse(String s, int id) {
                Log.e(TAG, "onResponse: " + s);

                final Gson gson = new Gson();
                final QNTokenBean qnTokenBean = gson.fromJson(s, QNTokenBean.class);
                if (qnTokenBean.getCode() == 200)
                {
                    Log.e(TAG, "onResponse: picPath+++   "+picPath.get(i)+" i+++   "+i);
                    File picFile = new File(picPath.get(i));
                    UploadManagerUtils.getUploadManager().put(picFile, qnTokenBean.getKey(), qnTokenBean.getToken(), new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject res) {
                            //res包含hash、key等信息，具体字段取决于上传策略的设置
                            index++;
                            if (info.isOK()) {
                                Log.i("qiniu", "res");
                                url.add(qnTokenBean.getUrl());
                                Log.e(TAG, "Url: "+qnTokenBean.getUrl() );
                                pic.add(qnTokenBean.getId());

                            } else {
                            }
                            if (index==picPath.size())
                            {
                                picNumber.setText(url.size()+"张");
                                releasePostAdapter.notifyDataSetChanged();
                                dismissLoadingDialog();
                            }
                            Log.e("qiniu", key + ", " + info + ", " + res);
                        }
                    }, null);
                }
            }
        });
    }


    @OnClick({R.id.return_auto, R.id.chat_evidence, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.return_auto:
                finish();
                break;
            case R.id.chat_evidence:
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Uri.Builder builder = Uri.parse("rong://" + this.getPackageName()).buildUpon();
                builder.appendPath("conversation").appendPath(getIntent().getStringExtra(LoongsConfig.ConversationType))
                        .appendQueryParameter("targetId", getIntent().getStringExtra(LoongsConfig.id))
                        .appendQueryParameter("title", "");
                Uri uri = builder.build();
                intent.setData(uri);
                //传入判断是否是消息多选功能
                intent.putExtra(LoongsConfig.is_chat_room_more,true);
                startActivityForResult(intent,100);
                break;
            case R.id.submit:
                complaint();
                break;
        }
    }

    private void complaint() {
        String message_uid="";
        String image_id="";
        String group_id="";
        String type="";
        if (TextUtils.isEmpty(reason.getText().toString()))
        {
            ToastUtils.showShort("请填写原因");
            return;
        }
        if (messages==null||messages.size()==0)
        {
            ToastUtils.showShort("请提交聊天信息");
            return;
        }
        if (getIntent().getStringExtra(LoongsConfig.ChatComplainType).equals(LoongsConfig.ComplainType.QUIT_GROUP.toString()))
        {
            type=LoongsConfig.ComplainType.GROUP.toString();
        }
        else{
            type=getIntent().getStringExtra(LoongsConfig.ChatComplainType);
        }

        for (String s : pic) {
            if (s.equals(pic))
            {
                image_id+=s;
            }
            image_id+=s+",";
        }
        for (Message message : messages) {
            if (message==messages.get(messages.size()-1))
            {
                message_uid+=message.getUId();
            }
            message_uid+=message.getUId()+",";
        }
        group_id=getIntent().getStringExtra(LoongsConfig.id);
        Log.e(TAG, "message_uid:  "+message_uid+"" );
        OkHttpUtils.get().url(UrlFactory.complaint())
                .addParams(LoongsConfig.id,getIntent().getStringExtra(LoongsConfig.objectId))
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.reason,reason.getText().toString())
                .addParams(LoongsConfig.type,type)
                .addParams(LoongsConfig.complaint_id,ComplaintID)
                .addParams(LoongsConfig.message_uid,message_uid)
                .addParams(LoongsConfig.image_id,image_id)
                .addParams(LoongsConfig.group_id,group_id)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "投诉nError: "+e );
                ToastUtils.showShort("投诉失败,请稍后重试");
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "投诉onResponse: "+response );
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code), jsonObject.getString(LoongsConfig.description));
                    if (jsonObject.getInt(LoongsConfig.code)==200)
                    {
                        ToastUtils.showShort("投诉成功");
                        if (getIntent().getStringExtra(LoongsConfig.ChatComplainType).equals(RongPushClient.ConversationType.PRIVATE))
                            MyApplication.removeRongyunConversation(Conversation.ConversationType.PRIVATE,getIntent().getStringExtra(LoongsConfig.id));
                        String ChatComplainType = getIntent().getStringExtra(LoongsConfig.ChatComplainType);
                        if (ChatComplainType.equals(LoongsConfig.ComplainType.GROUP_MEMBER.toString())){
                            //提出群成员
                            Complain complain = new Complain(Complain.Type.KICK_MEMBER, getIntent().getStringExtra(LoongsConfig.objectId));
                            EventBus.getDefault().post(complain);
                        }
                        else if (ChatComplainType.equals(LoongsConfig.ComplainType.PRIVATE.toString())){
                            //删除联系人好友
                            Complain complain = new Complain(Complain.Type.DELETE_FRIEND, getIntent().getStringExtra(LoongsConfig.objectId));
                            EventBus.getDefault().post(complain);
                        }
                        ComplaintsSuccessfullyActivity.start(ChatComplainActivity.this,getIntent().getStringExtra(LoongsConfig.ChatComplainType), getIntent().getStringExtra(LoongsConfig.objectId), getIntent().getStringExtra(LoongsConfig.id));
                        finish();
                    }
                    else if (jsonObject.getInt(LoongsConfig.code)==440001&&jsonObject.getInt(LoongsConfig.code)==440002){
                        ToastUtils.showShort(jsonObject.getString(LoongsConfig.description));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(List<Message> messages) {
        this.messages.clear();
        this.messages.addAll(messages);
        chatNumber.setText(messages.size()+"条聊天证据");
    }
    /**
     * 申请权限
     */
    @SuppressLint("NoCorrespondingNeedsPermission")
    @OnShowRationale({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForLocation(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("申请相机权限")
                .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForLocation() {
        Toast.makeText(this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForLocation() {
        Toast.makeText(this, getString(R.string.permission_never_ask), Toast.LENGTH_SHORT).show();
    }

    @NeedsPermission({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void startLocation() {
        MultiImageSelectorActivity.startSelect(ChatComplainActivity.this, 100, 9-url.size(), 1);
    }
    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
       ChatComplainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
